const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const fs = require('fs').promises
const path = require('path')

const app = express()
const PORT = process.env.PORT || 3000

// 中间件
app.use(cors())
app.use(bodyParser.json())
app.use(express.static('public'))

// 数据存储路径
const DATA_DIR = path.join(__dirname, 'data')
const ensureDataDir = async () => {
  try {
    await fs.mkdir(DATA_DIR, { recursive: true })
  } catch (error) {
    console.error('创建数据目录失败:', error)
  }
}

// API路由
// 费曼学习法数据
app.post('/api/feynman', async (req, res) => {
  try {
    await ensureDataDir()
    const data = {
      ...req.body,
      timestamp: new Date().toISOString()
    }
    await fs.writeFile(
      path.join(DATA_DIR, `feynman_${Date.now()}.json`),
      JSON.stringify(data, null, 2)
    )
    res.json({ success: true, message: '费曼学习数据已保存' })
  } catch (error) {
    res.status(500).json({ success: false, error: error.message })
  }
})

// 康奈尔笔记数据
app.post('/api/cornell', async (req, res) => {
  try {
    await ensureDataDir()
    const data = {
      ...req.body,
      timestamp: new Date().toISOString()
    }
    await fs.writeFile(
      path.join(DATA_DIR, `cornell_${Date.now()}.json`),
      JSON.stringify(data, null, 2)
    )
    res.json({ success: true, message: '康奈尔笔记已保存' })
  } catch (error) {
    res.status(500).json({ success: false, error: error.message })
  }
})

// 思维导图数据
app.post('/api/mindmap', async (req, res) => {
  try {
    await ensureDataDir()
    const data = {
      ...req.body,
      timestamp: new Date().toISOString()
    }
    await fs.writeFile(
      path.join(DATA_DIR, `mindmap_${Date.now()}.json`),
      JSON.stringify(data, null, 2)
    )
    res.json({ success: true, message: '思维导图已保存' })
  } catch (error) {
    res.status(500).json({ success: false, error: error.message })
  }
})

// IE七大手法数据
app.post('/api/ie-tools/:tool', async (req, res) => {
  try {
    await ensureDataDir()
    const tool = req.params.tool
    const data = {
      tool,
      ...req.body,
      timestamp: new Date().toISOString()
    }
    await fs.writeFile(
      path.join(DATA_DIR, `ie_${tool}_${Date.now()}.json`),
      JSON.stringify(data, null, 2)
    )
    res.json({ success: true, message: `${tool}数据已保存` })
  } catch (error) {
    res.status(500).json({ success: false, error: error.message })
  }
})

// 获取历史数据
app.get('/api/data/:type', async (req, res) => {
  try {
    await ensureDataDir()
    const type = req.params.type
    const files = await fs.readdir(DATA_DIR)
    const filteredFiles = files.filter(f => f.startsWith(type))
    
    const data = []
    for (const file of filteredFiles) {
      const content = await fs.readFile(path.join(DATA_DIR, file), 'utf8')
      data.push(JSON.parse(content))
    }
    
    res.json({ success: true, data: data.sort((a, b) => 
      new Date(b.timestamp) - new Date(a.timestamp)
    )})
  } catch (error) {
    res.status(500).json({ success: false, error: error.message })
  }
})

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() })
})

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`)
  console.log(`访问 http://localhost:${PORT} 查看应用`)
})